package com.gxa.global.filter;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.CustomizedToken;
import com.gxa.common.JwtResult;
import com.gxa.common.R;
import com.gxa.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义过滤器
 */
public class OAuth2Filter extends AuthenticatingFilter {

    //暂时不重写createToken方法
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return null;
    }

    //是访问允许
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        /**
         * 如何解决跨域请求中的OPTIONS请求：进行跨域请求的时候，并且请求头中有额外参数，比如token，客户端会先发送一个OPTIONS请求
         来探测后续需要发起的跨域POST请求是否安全可接受所以这个请求就不需要拦截
         */
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    //在访问被拒绝
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;
        httpServletResponse.setContentType("application/json;charset=utf-8");
        System.out.println("进入过滤器");
        String token = getRequestToken(httpServletRequest);
        R r = new R();
        //1. 获取请求token，如果token不存在，直接返回401
        if(token == null || "".equals(token)){
            r.setCode(401);
            r.setMsg("您还未登录！");
            httpServletResponse.getWriter().write(JSONObject.toJSONString(r));
            httpServletResponse.getWriter().flush();
            httpServletResponse.getWriter().close();
        }
        //2. 验证token是否合法
        JwtResult jwtResult = JwtUtils.validateJwt(token);
        if(jwtResult.isSuccess()){
            //合法
            //解析token
//            Claims claims = JwtUtils.parseJWT(token);//token中的获得用户名 和 密码
//            //解析token获得getSubject
//            CustomizedToken customizedToken = JSONObject.parseObject(claims.getSubject(),CustomizedToken.class);
//            //执行登录
//            getSubject(servletRequest,servletResponse).login(customizedToken);
            //执行登录 没有抛异常，就证明成功
            System.out.println("结束过滤器");
            return true;
        }else {
            //不合法
            //3. token过期
            if(jwtResult.getErrCode() == JwtUtils.JWT_ERRCODE_EXPIRE){
                r.setCode(jwtResult.getErrCode());
                r.setMsg("token 过期");


            }
            //4. token不合法
            if(jwtResult.getErrCode() == JwtUtils.JWT_ERRCODE_FAIL){
                r.setCode(jwtResult.getErrCode());
                r.setMsg("token 不合法");
            }
            httpServletResponse.getWriter().write(JSONObject.toJSONString(r));
            httpServletResponse.getWriter().flush();
            httpServletResponse.getWriter().close();
        }
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            R r = new R();
            r.setCode(401);
            r.setMsg(throwable.getMessage());
            String json = JSONObject.toJSONString(r);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("Authorization");
        //如果header中不存在token，则从参数中获取token
        if(token == null || "".equals(token)){
            token = httpRequest.getParameter("Authorization");
        }
        return token;
    }
}
